<?php
namespace Game\Controllers;

use Game\Module\Logger;
use GatewayWorker\Lib\Gateway;
use Game\Module\Tools;
use Game\Config\Config;
use Game\Lib\GlobalConst;
use Game\Lib\OptConst;
use Game\Models\Client\DispatcherClient;
use Game\Models\Server\DispatcherServer;

class Process{
	
	
    
    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     * 
     * @param int $client_id 连接id
     */
    public static function processOnConnect($client_id)
    {
	    //设备登陆
	    //$login_return_msg = "";
//	    Gateway::sendToClient($client_id, '{"result":"'.$client_id.'"}');
//	    var_dump($client_id);
	   
    }
    
    
    /**
    * 当用户断开连接时触发
    *
    * @param int $client_id 连接id
    */
    public static function processOnClose($client_id , $port , $data)
    {
        if($port == Config::GameClient_Port){
			$req_ary = $data;
	        $req_ary['client_id'] = $client_id;
	        $result = DispatcherClient::socketClosed($req_ary);
        }
    }


    /**
     * 数据处理入口
     *
     * @param int $client_id 连接id
     * @param string $message 具体消息
     * @param $port
     * @return bool
     */
    public static function processOnMessage($client_id, $message, $port)
    {
	    if($message == "@") {
		    Gateway::sendToClient($client_id, "@");
	    } else if(false != $message && $message != "") {
		    if($port == Config::GameClient_Port) {
			    //判断request格式是否正确
                $req_ary = Tools::getInstance()->checkupRequestFormat($message);
//                Logger::getInstance()->debug($req_ary);
			    $operation = GlobalConst::EMPTY_STRING;
			    if(is_array($req_ary) && !isset($req_ary['result'])) {
				    $req_ary['client_id'] = $client_id;
				    $operation = $req_ary['operation'];
				    
					//判断操作符
					$result = DispatcherClient::dispatcherOpt($req_ary);
			    } else {
				    $result = $req_ary;
			    }
			    
			    if($result != OptConst::NO_RETURN) {
				    //格式化返回结果
//                    Logger::getInstance()->debug($result);
                    $ret_result = Tools::getInstance()->formartReturn($result,$operation);
                    Logger::getInstance()->debug($ret_result);
				    //发送返回结果给client
				    Gateway::sendToClient($client_id, $ret_result);
			    }
		    } else if($port == Config::GameServer_Port) {
                //服务器推送模块
			    //判断request格式是否正确
                $req_ary =  Tools::getInstance()->checkupServerFormat($message);
			    if(is_array($req_ary)) {
				    $req_ary['client_id'] = $client_id;
				    $result = DispatcherServer::dispatcherOpt($req_ary);
			    } else {
				    $result = $req_ary;
			    }
			    if($result != OptConst::NO_RETURN) {
				    //格式化返回结果
				    //$ret_result = Process_Model::getModelObject()->formartReturn($result,$operation,$opcode,$request_params);
				    //发送返回结果给client
				    //Gateway::sendToClient($client_id, $ret_result);
			    }
		    }
	    }
	    return true;
	    
    }
}
?>